﻿using GDGeek;
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MrPP.SerriedCabinet
{
    public class CabinetSetup : MonoBehaviour
    {
        [SerializeField]
        private GridObjectCollection _grid;
        [SerializeField]
        private Cabinet _phototype;
        // Start is called before the first frame update
        List<Cabinet> list_ = null;
        public int count {
            get {
                return list_.Count;
            }
        }

        public Cabinet getCabinet(int i)
        {
            return list_[i];
        }

        public Task setup(int n) {

           
            TaskWait tw = new TaskWait(0);
            TaskManager.PushFront(tw, delegate
            {
                Cabinet[] cabinets = this.gameObject.GetComponentsInChildren<Cabinet>();
                foreach (var c in cabinets) {
                    GameObject.DestroyImmediate(c.gameObject);
                }
                for (int i = 0; i < n; ++i)
                {
                    Cabinet cabinet = GameObject.Instantiate(_phototype, this.transform, true);
                    cabinet.name = _phototype.name + "_" + i.ToString();
                    cabinet.gameObject.SetActive(true);
                }
                _grid.UpdateCollection();
            });
            TaskManager.PushBack(tw, delegate {

                Cabinet[] cabinets = this.gameObject.GetComponentsInChildren<Cabinet>();
                list_ = new List<Cabinet>(cabinets);
                list_.Sort((Cabinet left, Cabinet right) =>
                {
                    Debug.Log("x:"+left.transform.localPosition.x+":"+left.gameObject.name);
                    if (left.transform.localPosition.x > right.transform.localPosition.x)
                    {
                        return -1;
                    }
                    else if (left.transform.localPosition.x == right.transform.localPosition.x)
                    {
                        return 0;
                    }
                    return 1;

                });
                for (int i = 0; i < list_.Count; ++i)
                {
                    var l = list_[i];
                    Debug.Log(l.name + ":" + l.transform.localPosition.x);
                    l.id = i;
                    l.refresh();

                }   
            });
            return tw;
            //TaskManager.Run(tw);


        }
    }
}

